package br.com.winesys.geta.databinding.componentBinder;

import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.JRadioButton;
import br.com.winesys.geta.databinding.ComponentBinder;
import br.com.winesys.geta.databinding.component.selector.EnumSelector;

public final class EnumSelectorBinder implements ComponentBinder<EnumSelector<?>> {

	private static final ComponentBinder<EnumSelector<?>> INSTANCE = new EnumSelectorBinder();

	public static ComponentBinder<EnumSelector<?>> getInstance() {
		return INSTANCE;
	}

	private EnumSelectorBinder() {
	}

	@Override
	public Object read(EnumSelector<?> comp) {
		Enumeration<AbstractButton> e = comp.getButtonGroup().getElements();
		while (e.hasMoreElements()) {
			JRadioButton radio = (JRadioButton) e.nextElement();
			if (radio.isSelected()) {
				return radio.getClientProperty("value");
			}
		}
		return null;
	}

	@Override
	public void write(EnumSelector<?> component, Object value) {
		Enumeration<AbstractButton> e = component.getButtonGroup().getElements();
		while (e.hasMoreElements()) {
			JRadioButton radio = (JRadioButton) e.nextElement();
			if (radio.getClientProperty("value").equals(value)) {
				radio.setSelected(true);
				return;
			}
		}
	}
}
